<template>
  <div class="register">
    <div class="register-container">
      <h2>注册</h2>
      <form @submit.prevent="register">
        <div class="form-group">
          <label for="username">账号:</label>
          <input type="text" id="username" v-model="username" placeholder="请输入账号" required>
        </div>
        <div class="form-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="password" placeholder="请输入密码" required>
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认密码:</label>
          <input type="password" id="confirmPassword" v-model="confirmPassword" placeholder="请确认密码" required>
        </div>
        <button type="submit">注册</button>
        <p class="switch">已有账号？<router-link to="/">登录</router-link></p>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      confirmPassword: ''
    };
  },
  methods: {
    async register() {
      if (this.password !== this.confirmPassword) {
        alert('两次密码输入不一致');
        return;
      }

      try {
        const response = await fetch('http://82.156.19.25:5000/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            username: this.username,
            password: this.password
          })
        });
        const data = await response.json();
        if (data.success) {
          alert('注册成功');
          this.$router.push('/'); // 注册成功后跳转到登录页面
        } else {
          alert(data.message);
        }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  }
};
</script>
<style scoped>
html, body {
  height: 100%;
  margin: 0;
}

.register {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 100vh;           /* 高度设置为视口高度 */
}

.register-container {
  max-width: 400px;
  width: 100%;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
    margin-bottom: 20px;
    position: relative;
    display: flex;
}

label {
    margin-left: -20px;
    margin-top: 10px;
    width: 90px;
    display: block;
    margin-bottom: 5px;
    color: #555;
    font-weight: bold;
    margin-right: 5px;
}

input[type="text"],
input[type="password"] {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.switch {
  margin-top: 10px;
  color: #666;
}

.switch a {
  color: #4CAF50;
  text-decoration: none;
}

.switch a:hover {
  text-decoration: underline;
}

</style>
